/*
 * DeviceProtocol.cpp
 *
 *  Created on: Dec 8, 2011
 *      Author: kylintse
 */

#include "DeviceProtocol.h"
#include "ProtocolCan2Eth.h"
#include "rs485.h"
#include "gdata.h"
#include "BatteryStatus.h"

///////////////////////////////////////////////////////////////////////////////
// DeviceProtocol

DeviceProtocol::DeviceProtocol(quint32 id,const QString& devNode,
		KjDeviceList* lstDevice)
	: m_id(id),m_devNode(devNode),m_lstDevice(lstDevice)
{
	
}

DeviceProtocol::~DeviceProtocol()
{

}

///////////////////////////////////////////////////////////////////////////////
// DeviceProtocolRecycler
DeviceProtocolRecycler::DeviceProtocolRecycler(DeviceProtocol* protocol,QObject* parent/*=0*/)
	: kthread(parent),m_protocol(protocol)
{

}

DeviceProtocolRecycler::~DeviceProtocolRecycler()
{

}

void DeviceProtocolRecycler::run()
{
	setStarted(true);

	while(true)
	{
		if(needExit())
			break;

		m_protocol->recycle();

		msleep(5000);
	}

	setStarted(false);
}

///////////////////////////////////////////////////////////////////////////////
// DeviceProtocolManager
DeviceProtocolManager::DeviceProtocolManager(KjDeviceList* lstDevice)
	: m_lstDevice(lstDevice)
{

}

DeviceProtocolManager::~DeviceProtocolManager()
{

}

bool DeviceProtocolManager::startProtocol()
{
	ParamDeviceProtocol* protocolParm;
	DeviceProtocol* protocol;

	for(int i=0;i<gDeviceProtocolParam.size();i++)
	{
		protocolParm=gDeviceProtocolParam[i];

		if(protocolParm->type=="can-mpr")
		{
			protocol=new ProtocolCan2Eth(protocolParm->id,protocolParm->devNode,
					m_lstDevice);
		}
		else if(protocolParm->type=="rs485-test")
		{
			protocol=new rs485Test(protocolParm->id,protocolParm->devNode);
		}
		else if(protocolParm->type=="BatteryStatus")
		{
			protocol=new BatteryStatusQuery(protocolParm->id,
					protocolParm->devNode,m_lstDevice);
		}
		else
			continue;

		if(!protocol->start())
			return false;

		m_protocols.insert(protocolParm->id,protocol);
	}

	return true;
}
